<template>
  <div>
    <el-card shadow="always">
      <el-form :inline="true" ref="role" :model="role">
        <el-form-item label="编码:" prop="code">
          <el-input type="text" placeholder="编码" v-model="role.code"></el-input>
        </el-form-item>
        <el-form-item label="角色名称:" prop="name">
          <el-input type="text" placeholder="角色名称" v-model="role.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="dateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" :clearable="false"
                          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin-left: 20px">
          <el-button type="primary" @click="search"><i class="el-icon-search"></i> 搜索</el-button>
          <el-button @click="resetForm('role')"><i class="el-icon-refresh"></i> 重置</el-button>&nbsp;&nbsp;&nbsp;
          <el-dropdown>
            <el-button>更多 <i class="el-icon-arrow-down"></i></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="dialogVisible3 = true">
                添加
              </el-dropdown-item>
              <el-dropdown-item @click.native="dels">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </el-card>
    <el-divider></el-divider>
    <el-card class="box-card">
      <el-table :data="roleList" style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading"
                ref="multipleTable">
        <el-table-column type="selection" width="55" prop="pdAuthRole.id"></el-table-column>
        <el-table-column prop="pdAuthRole.code" label="编码" width="160"></el-table-column>
        <el-table-column prop="pdAuthRole.name" label="角色名称" width="160"></el-table-column>
        <el-table-column prop="pdAuthRole.describe" label="角色描述" width="200"></el-table-column>
        <el-table-column prop="pdAuthRole.readonly" label="是否内置" width="170">
          <template slot-scope="scope">
            <el-tag size="medium">{{ scope.row.pdAuthRole.readonly }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pdAuthRole.status" label="状态" width="160">
          <template slot-scope="scope">
            <el-tag size="medium">{{ scope.row.pdAuthRole.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pdAuthRole.createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button style="color: #009dff" type="text" size="medium" @click="updateId(scope.row)">编辑
            </el-button>
            <el-dropdown>
              <el-button type="text" style="border: none;color: #009dff">更多 <i class="el-icon-arrow-down"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="selUserAll(scope.row)" style="color: #009dff">
                  <i class="el-icon-user"></i>授权
                </el-dropdown-item>
                <el-dropdown-item @click.native="menuTree(scope.row.pdAuthRole.id)" style="color: #009dff">
                  <i class="el-icon-setting"></i>配置
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center">
        <br>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!--    添加-->
    <el-dialog title="新增" :visible.sync="dialogVisible3" class="width" :before-close="handleClose">
      <el-form :rules="rules" ref="rules" label-width="80px" :model="addrole">
        <el-form-item label="编码" prop="code">
          <el-input v-model="addrole.code"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addrole.name"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addrole.status">
            <el-radio-button label="true">启用</el-radio-button>
            <el-radio-button label="false">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色描述" prop="describe">
          <el-input v-model="addrole.describe"></el-input>
        </el-form-item>
        <el-form-item label="数据范围" prop="idList">
          <el-radio-group v-model="addrole.idList" size="medium">
            <el-radio-button :label="1">全部</el-radio-button>
            <el-radio-button :label="2">自定义</el-radio-button>
            <el-radio-button :label="3">个人</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="组织" v-if="addrole.idList === 2">
          <!--       组织树-->
          <el-tree :data="orgList" show-checkbox node-key="id" ref="insertTree" highlight-current default-expand-all
                   :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <span slot="footer" class="dialog-footer">
          <el-button @click="clearModel">取 消</el-button>
          <el-button type="primary" @click="adrole">确 定</el-button>
        </span>
      </div>
    </el-dialog>
    <!--    数据编辑-->
    <el-dialog title="修改" :visible.sync="dialogVisible" class="width" :before-close="handleClose">
      <el-form :rules="rules" ref="rules" label-width="80px" :model="uprole">
        <el-form-item label="编码" prop="code">
          <el-input v-model="uprole.code" readonly></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="uprole.name"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="uprole.status">
            <el-radio-button label="true">启用</el-radio-button>
            <el-radio-button label="false">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色描述" prop="describe">
          <el-input v-model="uprole.describe"></el-input>
        </el-form-item>
        <el-form-item label="数据范围" prop="idList">
          <el-radio-group v-model="uprole.idList" size="medium">
            <el-radio-button :label="1">全部</el-radio-button>
            <el-radio-button :label="2">自定义</el-radio-button>
            <el-radio-button :label="3">个人</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="组织" v-if="uprole.idList === 2">
          <!--       组织树-->
          <el-tree :data="orgList" show-checkbox node-key="id" ref="updateTree" highlight-current :check-strictly="true"
                   default-expand-all
                   :default-checked-keys="defOrgs" :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <span slot="footer" class="dialog-footer">
          <el-button @click="clearModel">取 消</el-button>
          <el-button type="primary" @click="update">确 定</el-button>
        </span>
      </div>
    </el-dialog>
    <!--    数据授权-->
    <el-dialog title="分配角色成员" :visible.sync="dialogVisible1" class="width" :before-close="handleClose">
      <div style="margin-left: 65px">
        <el-transfer filterable :filter-method="filterMethod" filter-placeholder="请输入用户名" v-model="value"
                     :data="data"></el-transfer>
        <div style="text-align: center;margin-left: -80px">
          <span slot="footer" class="dialog-footer">
              <el-button @click="clearModel">取 消</el-button>
              <el-button type="primary" @click="shouquan">确 定</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <!--    配置-->
    <el-dialog title="配置菜单资源" :visible.sync="dialogVisible2" width="65.5%" :before-close="handleClose">
      <el-row :gutter="18">
        <el-col :span="8" style="height : 380px;overflow : auto;">
          <el-card>
            <p>菜单</p>
            <el-tree :data="menuList" show-checkbox node-key="id" ref="menuTree" highlight-current
                     @node-click="handleNodeClick" :default-checked-keys="defMenus"
                     :check-strictly="true" default-expand-all :props="defaultProps1"></el-tree>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card>
            <p>资源</p>
            <el-table :data="tableData" ref="multipleTable1" :row-key="getRowKeys" tooltip-effect="dark"
                      style="width: 100%"
                      @selection-change="handleSelectionChange1">
              <el-table-column type="selection" :reserve-selection="true" width="55" prop="id"></el-table-column>
              <el-table-column label="编码" width="120" prop="code"></el-table-column>
              <el-table-column label="名称" prop="name" show-overflow-tooltip></el-table-column>
              <el-table-column label="请求方式" prop="method" show-overflow-tooltip></el-table-column>
              <el-table-column label="请求地址" prop="url" show-overflow-tooltip></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <div style="text-align: center;padding-top: 25px;">
        <span slot="footer" class="dialog-footer">
          <el-button @click="clearModel">取 消</el-button>
          <el-button type="primary" @click="peizhi">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import rolemanagement from "../../api/rightsmanagement/rolemanagement/rolemanagement";
import userManagement from "../../api/rightsmanagement/usermanagement/userManagement";

export default {
  name: "roleManagement",
  computed: {
    dateTime: {
      get() {
        if (this.role.startTime && this.role.stopTime) {
          return [this.role.startTime, this.role.stopTime]
        } else {
          return []
        }
      },
      set(v) {
        this.role.startTime = v[0]
        this.role.stopTime = v[1]
      }
    }
  },
  data() {
    return {
      loading: false,// 加载条
      role: {code: null, name: null, startTime: null, stopTime: null, num: null, size: null}, //表单信息
      currentPage: 1, //当前页
      pageSize: 5,  //一页几条
      total: 0,  //总条数
      roleList: [], //分页数据
      multipleSelection: [],
      multipleSelection1: [],
      delByIdLists: [],
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      orgStatus: {status: 1},
      orgList: {},
      menuList: [],
      roleAll: {},
      userList: [],
      userList1: [],
      data: [],
      value: [],
      filterMethod(query, item) {
        return item.name.indexOf(query) > -1;
      },
      // 设置树，名字，子集合
      defaultProps: {
        children: 'orgTreeDtoList',
        label: 'name'
      },
      // 设置树，名字，子集合
      defaultProps1: {
        children: 'pdMenu',
        label: 'name'
      },
      uprole: {id: null, code: null, name: null, status: null, describe: null, idList: null, readonly: null},
      addrole: {code: null, name: null, status: false, describe: null, idList: 3, readonly: null},
      roleById: {},
      menuRoleIds: [],
      rules: {
        name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}],
      },
      defOrgs: [],
      defMenus: [],
      orgIdAll: [],
      dto: {pdAuthRole: null, idList: null},
      menudto: {idList: null, roleId: null, buttonList: null},
      tableData: [],
      quanxian: {},
      list: []
    }
  },
  methods: {
    roles() {
      this.role.num = this.currentPage
      this.role.size = this.pageSize
      rolemanagement.selRoleAll(this.role).then(({data}) => {
        this.roleList = data.data.records
        this.total = data.data.total
        this.loading = false
      })
    },
    search() {
      this.loading = true
      this.roles();
    },
    adrole() {
      if (this.addrole.idList === 1) {
        this.dto.pdAuthRole = this.addrole
        this.dto.idList = this.orgIdAll
        rolemanagement.addRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.clearModel('rules');
        })
      } else if (this.addrole.idList === 2) {
        this.dto.pdAuthRole = this.addrole
        let checkedKeys = this.$refs.insertTree.getCheckedKeys();
        this.dto.idList = checkedKeys
        rolemanagement.addRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.clearModel('rules');
        })
      } else {
        this.dto.pdAuthRole = this.addrole
        this.orgIdAll = [];
        this.dto.idList = this.orgIdAll
        rolemanagement.addRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.clearModel('rules');
        })
      }
    },
    panduan(data) {
      if (data.code === 200) {
        this.$message({
          message: data.message,
          type: 'success'
        });
      } else {
        this.$message.error(data.message);
      }
    },
    update() {
      if (this.uprole.idList === 1) {
        this.dto.pdAuthRole = this.uprole
        this.dto.idList = this.orgIdAll
        rolemanagement.updateRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.dialogVisible = false;
          this.roles();
        })
      } else if (this.uprole.idList === 2) {
        this.dto.pdAuthRole = this.uprole
        let checkedKeys = this.$refs.updateTree.getCheckedKeys();
        this.dto.idList = checkedKeys
        rolemanagement.updateRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.dialogVisible = false;
          this.roles();
        })
      } else {
        this.dto.pdAuthRole = this.uprole
        this.orgIdAll = [];
        this.dto.idList = this.orgIdAll
        rolemanagement.updateRole(this.dto).then(({data}) => {
          this.panduan(data)
          this.dialogVisible = false;
          this.roles();
        })
      }

    },
    dels() {
      this.$confirm('此操作将永久删除选择的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.multipleSelection.forEach(e => {
          this.delByIdLists.push(e.pdAuthRole.id)
        })
        let wd = {idList: this.delByIdLists}
        if (wd.idList.length !== 0) {
          rolemanagement.delByIds(wd).then(({data}) => {
            if (data.code === 200) {
              if (data.message === "角色全部删除成功") {
                this.$message({
                  message: data.message,
                  type: 'success'
                });
              } else {
                this.delByIdLists = [];
                this.$message({
                  message: data.message,
                  type: 'warning'
                });
              }
            } else {
              this.delByIdLists = [];
              this.$message.error(data.message);
            }
            this.roles()
          })
        } else {
          this.$message({
            message: '未选择删除的选项',
            type: 'warning'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    updateId(rows) {
      this.dialogVisible = true;
      this.uprole.id = rows.pdAuthRole.id
      this.uprole.code = rows.pdAuthRole.code;
      this.uprole.name = rows.pdAuthRole.name;
      this.uprole.status = rows.pdAuthRole.status;
      this.uprole.describe = rows.pdAuthRole.describe;
      rolemanagement.selectOrgAll().then(({data}) => {
        data.data.forEach(e => {
          this.orgIdAll.push(e.id)
        })
        this.defOrgs = rows.roleOrgsId
        if (rows.roleOrgsId.length !== 0) {
          if (data.data.length === rows.roleOrgsId.length) {
            this.uprole.idList = 1
          } else {
            this.uprole.idList = 2
          }
        } else {
          this.uprole.idList = 3
        }
      })
    },
    selOrgAll() {
      rolemanagement.selOrgAll(this.orgStatus).then(({data}) => {
        this.dg(data.data)
        this.orgList = data.data
      })
    },
    selUserAll(row) {
      this.roleById = row.pdAuthRole.id
      this.$store.commit("startAnimation", true);
      userManagement.selUserAll(row.pdAuthRole.id).then(({data}) => {
        //未有  左侧
        this.dialogVisible1 = true
        data.data.didNotHaveUsers.forEach((e, i) => {
          this.userList.push(e.name)
          this.data.push({
            label: e.name,
            key: e.id,
            name: this.userList[i]
          })
        })
        //已有
        data.data.didHaveUsers.forEach((w, q) => {
          this.userList.push(w.name)
          this.data.push({
            label: w.name,
            key: w.id,
            name: this.userList[q]
          })
        })
        //右侧
        data.data.didHaveUsers.forEach(w => {
          this.userList1.push(w.name)
          this.value.push(w.id)
        })

        this.$store.commit("startAnimation", false);
      })

    },
    shouquan() {
      this.$store.commit("startAnimation", true)
      let list = {idList: this.value, roleId: this.roleById}
      rolemanagement.shouquan(list).then(({data}) => {
        this.$store.commit("startAnimation", false)
        this.dialogVisible1 = false
        if (data.code === 200) {
          this.$message({
            message: data.message,
            type: 'success'
          });
        } else {
          this.$message.error(data.message);
        }
      })
      this.data = [];
      this.value = [];
    },
    menuTree(rows) {
      const status = {menuStatus: 1}
      this.menudto.roleId = rows
      rolemanagement.getMenu(status).then(({data}) => {
        this.dgMenu(data.data)
        this.menuList = data.data
      })
      this.$store.commit("startAnimation", true);
      rolemanagement.getMenuQuanxian(rows).then(({data}) => {
        this.$store.commit("startAnimation", false);
        this.quanxian = data.data
        data.data.menus.forEach(e => {
          this.menuRoleIds.push(e.id)
        })
        this.defMenus = this.menuRoleIds;
        this.dialogVisible2 = true
        this.quanxian.buttons.forEach(e => {
          this.$nextTick(() => {
            this.$refs.multipleTable1.toggleRowSelection(e, true)
          })
        })
      })
    },
    // 点击菜单触发
    handleNodeClick(obj) {
      this.list = obj.id
      let arr = []
      rolemanagement.getMenuId(obj.id).then(({data}) => {
        data.data.forEach(e => {
          arr[arr.length] = e
        })
        this.tableData = arr
      })
    }
    ,
    peizhi() {
      //获取选中的菜单集
      let checkedKeys = this.$refs.menuTree.getCheckedKeys();
      let list = []
      this.multipleSelection1.forEach(e => {
        list.push(e.id)
      })
      this.menudto.idList = checkedKeys
      this.menudto.buttonList = list
      this.$store.commit("startAnimation", true);
      rolemanagement.peizhiMenu(this.menudto).then(({data}) => {
        this.$store.commit("startAnimation", false);
        if (data.code === 200) {
          this.$message({
            message: data.message,
            type: 'success'
          });
        } else {
          this.$message.error(data.message);
        }
      })
      this.dialogVisible2 = false
      this.$refs.multipleTable1.clearSelection()
    }
    ,
    clearModel() {
      this.data = [];
      this.value = [];
      this.menuRoleIds = [];
      this.defMenus = [];
      this.tableData = [];
      this.dialogVisible1 = false;
      this.dialogVisible = false;
      this.dialogVisible3 = false;
      this.dialogVisible2 = false;
      this.addrole = {code: null, name: null, status: false, describe: null, idList: 3, readonly: null}
      this.roles();
    }
    ,
    handleClose() {
      this.$confirm('确认关闭？').then(_ => {
        this.clearModel();
      }).catch(_ => {
      });
    }
    ,
    resetForm(role) {
      this.$refs[role].resetFields();
      this.role.startTime, this.role.stopTime = null
    }
    ,
    handleSizeChange(val) {
      this.pageSize = val
      this.loading = true
      this.roles()
    }
    ,
    handleCurrentChange(val) {
      this.currentPage = val
      this.loading = true
      this.roles()
    }
    ,
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
    ,
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    }
    ,
    // 处理orgTree数据
    dg(data) {
      if (data != null) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].orgTreeDtoList.length > 0) {
            this.dg(data[i].orgTreeDtoList)
          }
          this.$set(data[i], 'name', data[i].pdCoreOrg.name)
          this.$set(data[i], 'id', data[i].pdCoreOrg.id)
        }
      }
    }
    ,
    // 处理menuTree数据
    dgMenu(data) {
      if (data != null) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].pdMenu.length > 0) {
            this.dgMenu(data[i].pdMenu)
          }
          this.$set(data[i], 'name', data[i].pdAuthMenu.name)
          this.$set(data[i], 'id', data[i].pdAuthMenu.id)
        }
      }
    }
    ,
    getRowKeys(row) {
      return row.id
    }
  },
  created() {
    this.loading = true
    this.roles()
    this.selOrgAll()
  }
}
</script>
<style>
.width {
  width: auto;
}
</style>
